<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace backend\controllers;

use Yii;
use yii\web\AdminController;

class ProductController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'product';

    //基础产品
    public function actionIndex()
    {
        $sql = 'select * from product_category';
        $list = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        return $this->render('index', ['category' => $list]);
    }

    //产品分类
    public function actionCategory()
    {
        return $this->render('category');
    }

    //销售产品分类
    public function actionSaleCategory()
    {
        return $this->render('sale-category');
    }

    //销售产品分类
    public function actionSaleProduct()
    {
        $sql = 'select * from item_category';
        $list = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        return $this->render('sale-product', ['category' => $list]);
    }

    //基础产品 ajax list
    public function actionGetList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select pm.*,pc.name as categoryName from product_master pm
                    inner join product_category pc on pm.categoryId=pc.categoryId WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT FROM product_master pm
                    inner join product_category pc on pm.categoryId=pc.categoryId WHERE 1=1 ';

        if (isset($data['name']) && !empty($data['name'])) {
            $sql .= ' AND pm.name like "%' . $data['name'] . '%"';
        }
        if (isset($data['category']) && !empty($data['category'])) {
            $sql .= ' AND pm.categoryId =' . $data['category'];
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY pm.productId';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        //$this->saveLog($this->service, '产品列表', 'VIEW', '产品列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //保存基础产品
    public function actionSaveProduct()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['categoryId'] = $data['categoryId'];
        $model['name'] = $data['productName'];
        $model['sort'] = $data['sort'];
        $model['useflg'] = $data['useflg'];

        if (empty($data['id'])) {
            $ckSql = "select count(0) cnt from product_master where name='" . $data['productName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $sql = 'select max(productId) as productId from product_master where categoryId=' . $data['categoryId'];
            $maxId = Yii::$app->db_assemble->createCommand($sql)->queryOne();
            if ($maxId && $maxId['productId']) {
                $productId = $maxId['productId'] + 1;
            } else {
                $productId = $data['categoryId'] . '001';
            }
            $model['productId'] = $productId;
            $model['creator'] = $this->getCreator();
            $model['createtime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->insert('product_master', $model)->execute();
        } else {
            $ckSql = "select count(0) cnt from product_master where AutoId<>" . $data['id'] . " and name='" . $data['productName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }
            $model['updator'] = $this->getCreator();
            $model['updatetime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->update('product_master', $model, ['AutoId' => $data['id']])->execute();
        }

        if ($res) {
            $this->retJson('保存成功', 200);
        }
        $this->retJson('操作失败', 500);
    }

    //基础产品详情
    public function actionGetProduct()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['id']) || empty($data['id'])) {
            $this->retJson('参数错误', 500);
        }
        $sql = 'select * from product_master WHERE AutoId=' . $data['id'];
        $result = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('ok', 200, $result);
    }

    //分类 ajax list
    public function actionCategoryList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'SELECT * FROM product_category WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT FROM product_category WHERE 1=1 ';

        if (isset($data['name']) && !empty($data['name'])) {
            $sql .= ' AND name like "%' . $data['name'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY categoryId';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        //$this->saveLog($this->service, '产品列表', 'VIEW', '产品列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //分类明细
    public function actionCategoryDtl()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['id']) || empty($data['id'])) {
            $this->retJson('参数错误', 500);
        }
        $sql = 'select * from product_category WHERE AutoId=' . $data['id'];
        $result = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('ok', 200, $result);
    }

    //保存分类
    public function actionSaveCategory()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['name'] = $data['categoryName'];
        $model['sort'] = $data['sort'];
        $model['useflg'] = $data['useflg'];

        if (empty($data['id'])) {
            $ckSql = "select count(0) cnt from product_category where categoryId='" . $data['categoryId'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('编号已存在', 500);
            }

            $ckSql = "select count(0) cnt from product_category where name='" . $data['categoryName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $model['categoryId'] = $data['categoryId'];
            $model['creator'] = $this->getCreator();
            $model['createtime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->insert('product_category', $model)->execute();
        } else {
            $ckSql = "select count(0) cnt from product_category where AutoId<>" . $data['id'] . " AND name='" . $data['categoryName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $model['updator'] = $this->getCreator();
            $model['updatetime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->update('product_category', $model, ['AutoId' => $data['id']])->execute();
        }

        if ($res) {
            $this->retJson('保存成功', 200);
        }
        $this->retJson('操作失败', 500);
    }


    //分类 ajax list
    public function actionSaleCategoryList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'SELECT * FROM item_category WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT FROM item_category WHERE 1=1 ';

        if (isset($data['name']) && !empty($data['name'])) {
            $sql .= ' AND name like "%' . $data['name'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY categoryId';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        //$this->saveLog($this->service, '产品列表', 'VIEW', '产品列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //分类明细
    public function actionSaleCategoryDtl()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['id']) || empty($data['id'])) {
            $this->retJson('参数错误', 500);
        }
        $sql = 'select * from item_category WHERE AutoId=' . $data['id'];
        $result = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('ok', 200, $result);
    }

    //保存分类
    public function actionSaveSaleCategory()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['name'] = $data['categoryName'];
        $model['sort'] = $data['sort'];
        $model['useflg'] = $data['useflg'];

        if (empty($data['id'])) {
            $ckSql = "select count(0) cnt from item_category where categoryId='" . $data['categoryId'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('编号已存在', 500);
            }
            $ckSql = "select count(0) cnt from item_category where name='" . $data['categoryName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $model['categoryId'] = $data['categoryId'];
            $model['creator'] = $this->getCreator();
            $model['createtime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->insert('item_category', $model)->execute();
        } else {
            $ckSql = "select count(0) cnt from item_category where AutoId<>" . $data['id'] . " AND name='" . $data['categoryName'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $model['updator'] = $this->getCreator();
            $model['updatetime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->update('item_category', $model, ['AutoId' => $data['id']])->execute();
        }

        if ($res) {
            $this->retJson('保存成功', 200);
        }
        $this->retJson('操作失败', 500);
    }

    //销售产品 ajax list
    public function actionSaleProductList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select im.*, ic.name as categoryName,pm.name as keyName FROM item_master im
                    inner join item_category ic on im.categoryId=ic.categoryId
                    left join product_master pm on im.key_productId=pm.productId WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT FROM item_master im
                    inner join item_category ic on im.categoryId=ic.categoryId WHERE 1=1 ';

//        if (isset($data['keyName']) && !empty($data['keyName'])) {
//            $sql .= ' AND pm.name like "%' . $data['name'] . '%"';
//        }
        if (isset($data['name']) && !empty($data['name'])) {
            $sql .= ' AND im.name like "%' . $data['name'] . '%"';
        }
        if (isset($data['inside_name']) && !empty($data['inside_name'])) {
            $sql .= ' AND im.inside_name like "%' . $data['inside_name'] . '%"';
        }
        if (isset($data['category']) && !empty($data['category'])) {
            $sql .= ' AND im.categoryId =' . $data['category'];
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY im.itemId';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        //$this->saveLog($this->service, '产品列表', 'VIEW', '产品列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //销售产品明细
    public function actionSaleProductDtl()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['id']) || empty($data['id'])) {
            $this->retJson('参数错误', 500);
        }
        $sql = 'select * from item_master WHERE AutoId=' . $data['id'];
        $result = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('ok', 200, $result);
    }

    //保存销售产品
    public function actionSaveSaleProduct()
    {
        $data = Yii::$app->request->post();
        $model = array();
        $model['name'] = $data['name'];
        $model['inside_name'] = $data['inside_name'];
        $model['price'] = $data['price'];
        $model['pack_price'] = $data['pack_price'];
        $model['sort'] = $data['sort'];
        $model['useflg'] = $data['useflg'];
        $model['categoryId'] = $data['categoryId'];

        if (empty($data['id'])) {
            $ckSql = "select count(0) cnt from item_master where name='" . $data['name'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }
            $sql = 'select max(itemId) as productId from item_master where categoryId=' . $data['categoryId'];
            $maxId = Yii::$app->db_assemble->createCommand($sql)->queryOne();
            if ($maxId && $maxId['productId']) {
                $itemId = $maxId['productId'] + 1;
            } else {
                $itemId = $data['categoryId'] . '00001';
            }

            $model['itemId'] = $itemId;
            $model['creator'] = $this->getCreator();
            $model['createtime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->insert('item_master', $model)->execute();
        } else {
            $ckSql = "select count(0) cnt from item_master where AutoId<>" . $data['id'] . " and name='" . $data['name'] . "'";
            $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
            if ($ck_count && $ck_count['cnt']) {
                $this->retJson('名称已存在', 500);
            }

            $model['updator'] = $this->getCreator();
            $model['updatetime'] = date('Y-m-d H:i:s');
            $res = Yii::$app->db_assemble->createCommand()->update('item_master', $model, ['AutoId' => $data['id']])->execute();
        }

        if ($res) {
            $this->retJson('保存成功', 200);
        }
        $this->retJson('操作失败', 500);
    }

    //查询匹配的商品信息
    public function actionSearchProduct()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['keyName']) || empty($data['keyName']) || !isset($data['itemId']) || empty($data['itemId'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "select count(0) as CNT from product_master pm
                inner join item_detail id on id.productId=pm.productId 
                where (pm.productId='" . $data['keyName'] . "' OR pm.name ='" . $data['keyName'] . "') and id.itemId=" . $data['itemId'];
        $res_cnt = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        if ($res_cnt && $res_cnt['CNT']) {
            $this->retJson('商品已存在', 500);
        }

        $sql = "select pm.*,pc.name as categoryName from product_master pm
                inner join product_category pc on pm.categoryId=pc.categoryId 
                where (pm.productId='" . $data['keyName'] . "' OR pm.name ='" . $data['keyName'] . "')";
        $result = Yii::$app->db_assemble->createCommand($sql)->queryOne();

        $this->retJson('ok', 200, $result);
    }

    //查询产品关系
    public function actionGetMatchProduct()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['itemId']) || empty($data['itemId'])) {
            $this->retJson('参数错误', 500);
        }
        $sql = 'select pm.productId,pm.name as productName,pc.name as categoryName,im.key_productId from item_detail id
            inner join product_master pm on id.productId=pm.productId
            inner join product_category pc on pm.categoryId=pc.categoryId
            left join item_master im on im.itemId=id.itemId and pm.productId=im.key_productId
            where id.itemId=' . $data['itemId'];
        $result = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        $this->retJson('ok', 200, $result);
    }

    //保存关联商品
    public function actionSaveMatchProduct()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['itemId']) || empty($data['itemId']) ||
            !isset($data['productId']) || empty($data['productId']) ||
            !isset($data['key_productId']) || empty($data['key_productId'])) {
            $this->retJson('参数错误', 500);
        }
        $creator = $this->getCreator();
        $createtime = date('Y-m-d H:i:s');
        $transaction = Yii::$app->db_assemble->beginTransaction();
        try {
            $sql = 'delete from item_detail where itemId=' . $data['itemId'];
            Yii::$app->db_assemble->createCommand($sql)->execute();

            foreach ($data['productId'] as $productId) {
                $model = array(
                    'itemId' => $data['itemId'],
                    'productId' => $productId,
                    'useflg' => 1,
                    'creator' => $creator,
                    'createtime' => $createtime,
                );
                Yii::$app->db_assemble->createCommand()->insert('item_detail', $model)->execute();
            }
            $sql = 'update item_master set key_productId=' . $data['key_productId'] . ' where itemId=' . $data['itemId'];
            Yii::$app->db_assemble->createCommand($sql)->execute();
            $transaction->commit();
            $this->retJson('保存成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    public function getCreator()
    {
        $userInfo = \common\helps\tools::getloginUserInfo();
        if ($userInfo) {
            $userName = $userInfo->userName;
        } else {
            $userName = '';
        }
        return $userName;
    }
}